package com.qm.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 @author james
 @create 2021-04-28 19:44
 CookieAPI工具类
 */
public class CookieUtil {

    /**
     * 添加cookie
     * @param cookieName   cookie名称
     * @param cookieValue  cookie值
     * @param domain
     * @param maxAge       存活时间
     * @param response
     */
    public static void addCookie(String cookieName, String cookieValue, String domain,
                                 Integer maxAge, HttpServletResponse response) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setPath("/");
        cookie.setDomain(domain);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 根据Cookie的名称，获取Cookie对象
     * @param cookieName   cookie名称
     * @param request
     * @return
     */
    public static Cookie getCookieValue(String cookieName, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length >0 ) {
            for (Cookie cookie : cookies ) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 删除Cookie
     * @param response
     * @param cookieName
     * @param domain
     */
    public static void deleteCookie(HttpServletResponse response, String cookieName, String domain) {
        Cookie cookie = new Cookie(cookieName, "");
        cookie.setDomain(domain);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

}
